package com.me.controllers;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.socket.TextMessage;

import com.me.bean.AjaxResp;
import com.me.bean.FileUpLoadMsgBean;
import com.me.bean.JsonDateStructure;
import com.me.entity.FileMapping;
import com.me.entity.NewsRecords;
import com.me.entity.UserInfo;
import com.me.service.FileUploadService;
import com.me.service.GroupChatMsgDataService;
import com.me.service.GroupService;
import com.me.service.SingleCharMsgService;
import com.me.service.SingleChatMsgDataService;
import com.me.service.UserInfoService;
import com.me.service.WebSocketHandler;
import com.me.util.GetRandomStr;
import com.me.util.GetTIme;
import com.me.util.ImageUtil;
import com.me.util.MapUtil;

@Controller
public class UploadFileControl {

	@Autowired
	UserInfoService userInfoService; 
	
	
	@Autowired
	GroupChatMsgDataService groupChatMsgDataService;
	@Autowired
	SingleCharMsgService singleCharMsgService; 
	@Autowired
	SingleChatMsgDataService singleChatMsgDataService;
	@Autowired
	WebSocketHandler ws;
	@Autowired
	GroupService groupService;
	@Autowired
	FileUploadService fileUploadService; 
	
	@RequestMapping(value="/headicon",method=RequestMethod.POST)
	@Transactional
	@ResponseBody
	public AjaxResp headicon(@RequestParam("file") CommonsMultipartFile file,@RequestParam("account") String account,HttpServletRequest  request){
		//上传头像
		AjaxResp ar=new AjaxResp();
		ar.setSuccess(false);
		System.out.println("得到参数:"+file.getOriginalFilename()+" account:"+account);
		
		
		File destFolder=new File("E:\\FeiGe_Source\\"+account+"\\imgs\\");
		String newFileName=destFolder+"\\"+account+"_headicon.jpg";
		
		if(!destFolder.exists()){
			ImageUtil.createFolder("E:\\FeiGe_Source\\"+account+"\\imgs\\");
		}
		try {
			ImageUtil.resizeImgToJpeg(file.getInputStream(), 40, 40,newFileName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			return ar;
		}
		//将数据更新进数据库
		
		
		UserInfo ui=(UserInfo)userInfoService.getUserByAccount(account).get(0);
		ui.setIcon(newFileName);
		
		userInfoService.update(ui);
		ar.setSuccess(true);
		ar.setData(account);
		
		return ar;
	}
	
	

	@RequestMapping("send_file")
	@ResponseBody
	@Transactional
	public synchronized AjaxResp sendFile(@RequestParam("file") CommonsMultipartFile file,@RequestParam("account") String account,String chat_type,String friAccount,HttpServletRequest  request) throws IOException{
		AjaxResp ar=new AjaxResp();
		FileMapping fm=new FileMapping();
		
		ar.setSuccess(false);
		
		
		String mappingFilename="";
		String newBaseFileName="";
		String OriBaseFileName="";
		String OriFileName="";
		String newFileName="";
		String newsType="file";
		String random_str=GetRandomStr.generateRandomStr(15);
		NewsRecords nr=new NewsRecords();
		fm.setUid(userInfoService.getUserIdByAccount(account));
		fm.setTime(GetTIme.getNowTime());
		if(chat_type.equals("single")){
			
			
			nr.setContent("");
			nr.setType(newsType);
			nr.setCtime(GetTIme.getNowTime());
			nr.setIsread(0);
			nr.setSuid(userInfoService.getUserIdByAccount(account));
			nr.setRuid(userInfoService.getUserIdByAccount(friAccount));
			
			singleCharMsgService.save(nr);
			
		}
		int id=0;
		 newBaseFileName="E:\\FeiGe_Source\\"+chat_type+"\\";
		 OriBaseFileName="E:\\FeiGe_Source\\"+chat_type+"\\";
		 if(chat_type.equals("group")){
				id=Integer.parseInt(friAccount);
				
			}else{
				id=nr.getId();
			}
		
		
		//判断用户上传的文件是否为图片文件
		if(ImageUtil.isImage(file.getInputStream())){
			//是图片文件
			newsType="img";
			
			
			System.out.println("上传的是图片文件");
			Image img=ImageIO.read(file.getInputStream());
			int ori_width=img.getWidth(null);
			int ori_height=img.getHeight(null);
			double new_height=0;
			double new_width=0;
			System.out.println("得到原图高度："+ori_height+"，，宽度："+ori_width);
			double rate=(double)ori_height/ori_width;
//			 newBaseFileName="E:\\FeiGe_Source\\"+chat_type+"_chat\\new_img\\"+nr.getId()+"\\";
//			 OriBaseFileName="E:\\FeiGe_Source\\"+chat_type+"_chat\\ori_img\\"+nr.getId()+"\\";
			
			if(!new File(newBaseFileName).exists()){
				ImageUtil.createFolder(newBaseFileName);
			}
			
			if(chat_type.equals("group")){
				
				newFileName=newBaseFileName+id+"\\"+"new_"+random_str+".jpg";
				if(!new File(newBaseFileName+id+"\\").exists()){
					ImageUtil.createFolder(newBaseFileName+id+"\\");
				}
				
					
					
					OriFileName=OriBaseFileName+id+"\\"+random_str+"."+ImageUtil.getPrefix(file.getOriginalFilename());
					mappingFilename=random_str+"."+ImageUtil.getPrefix(file.getOriginalFilename());
			}else{
				newFileName=newBaseFileName+"new_"+random_str+".jpg";
				OriFileName=OriBaseFileName+random_str+"."+ImageUtil.getPrefix(file.getOriginalFilename());
				mappingFilename=random_str+"."+ImageUtil.getPrefix(file.getOriginalFilename());
			}
			 
		System.out.println("height/width:"+rate);
			if(ori_height>200 || ori_width>200){
				System.out.println("需要压缩");
				
				
				
				if(ori_height>=ori_width){
					rate=(double)ori_width/ori_height;
					new_height=200;
					new_width=new_height*rate;
					ImageUtil.resizeImgToJpeg(file.getInputStream(), (int)new_width, (int)new_height, newFileName);
					
					
					
					
					
				}else{
					rate=(double)ori_height/ori_width;
					new_width=200;
					new_height=new_width*rate;
					ImageUtil.resizeImgToJpeg(file.getInputStream(), (int)new_width, (int)new_height, newFileName);
					
				}
				
				
				
				
				
			}else{
				System.out.println("不需要亚索");
				ImageUtil.resizeImgToJpeg(file.getInputStream(), ori_width, ori_height, newFileName);
			
			}
			
			
			//保存原图
			
			
			ImageUtil.saveOriFile(OriFileName, file.getInputStream());
			
			fm.setOrifilename(file.getOriginalFilename());
			mappingFilename=random_str+"."+ImageUtil.getPrefix(file.getOriginalFilename());
			fm.setNewfilename(mappingFilename);
			fm.setTime(GetTIme.getNowTime());
			
		}else{
			
			System.out.println("上传的是其它文件");
			newsType="file";
			if(chat_type.equals("group")){
				OriFileName=OriBaseFileName+id+"\\"+random_str+"."+ImageUtil.getPrefix(file.getOriginalFilename());
				mappingFilename=random_str+"."+ImageUtil.getPrefix(file.getOriginalFilename());
					
				//OriFileName=OriBaseFileName+id+"//"+code+file.getOriginalFilename();
					
			}else{
				
				OriFileName=OriBaseFileName+random_str+"."+ImageUtil.getPrefix(file.getOriginalFilename());
				mappingFilename=random_str+"."+ImageUtil.getPrefix(file.getOriginalFilename());
			}
			if(!new File(OriBaseFileName+id+"\\").exists()){
				ImageUtil.createFolder(OriBaseFileName+id+"\\");
			}
			ImageUtil.saveOriFile(OriFileName, file.getInputStream());
			//fm.setNewfilename(newFileName);
			fm.setOrifilename(file.getOriginalFilename());
			fm.setNewfilename(mappingFilename);
		}
		
		
		
			
			if(newsType.equals("img")){
				nr.setContent(newFileName);
			}else{
				nr.setContent(OriFileName);
				newFileName=file.getOriginalFilename();
			}
			
			nr.setType(newsType);
			if(chat_type.equals("single")){
				singleCharMsgService.UpdateMsgStateById(nr);
				fm.setNewfilename(mappingFilename=random_str+"."+ImageUtil.getPrefix(file.getOriginalFilename()));
			}
			fm.setNewfilename(mappingFilename=random_str+"."+ImageUtil.getPrefix(file.getOriginalFilename()));
			fileUploadService.save(fm);
			
			
			
			//转发消息
			
			if(chat_type.equals("single")){
				System.out.println("向单聊用户转发消息");
				String msg=newsType;
				System.out.println("singlechatmsgserver------>id:"+nr.getId());
				//String msg_="{\"msg_id\":\""+nr.getId()+"\",\"msg\":\""+msg+"\",\"new_src\":\""+newFileName+"\",\"ori_src\":\""+OriFileName+"\"}";
				
				FileUpLoadMsgBean fum=new FileUpLoadMsgBean();
				fum.setMsg_id(nr.getId());
				fum.setMsg(msg);
				fum.setNew_src(newFileName);
				fum.setOri_src(OriFileName);
				String msg_=fum.toJson();
				
				
				JsonDateStructure jds = new JsonDateStructure();
				jds.setDatetype(newsType);
				jds.setMsgcontent(msg_);
				jds.setResptype("singlechat");
				jds.setReceiver(friAccount);
				jds.setSender(account);
				jds.setDate(GetTIme.getNowTime());
				
				System.out.println("------响应数据：构建完成");
				if (WebSocketHandler.isOnline(friAccount)) {
					// 构建转发数据
					System.out.println("------用户在线");
					
					System.out.println("------数据保存完毕");
					

					String respMsg_toreceiver = jds.toJson();
					Map<String,TextMessage> se=new HashMap<>();
					se.put(friAccount, new TextMessage(respMsg_toreceiver));
					
					String respMsg_tosender = jds.toJson();
					se.put(account, new TextMessage(respMsg_toreceiver));
					
					ws.sendMsgToUsers(se);
					
					
					
					
				}else{
					jds.setReceiver(friAccount);
					String respMsg_tosender = jds.toJson();
					ws.sendMsgToUser(account, new TextMessage(respMsg_tosender));
				}
				
			}else{
				//向群聊用户转发消息
				FileUpLoadMsgBean fum=new FileUpLoadMsgBean();
				fum.setMsg_id(id);
				fum.setNew_src(newFileName);
				fum.setOri_src(OriFileName);
				fum.setMsg(newsType);
				String msg_=fum.toJson();
				
//				
//				JsonDateStructure jds=new JsonDateStructure();
//				jds.setDatetype(newsType);
//				jds.setDate(GetTIme.getNowTime());
//				jds.setMsgcontent(msg_);
//				jds.setResptype("groupchat");
//				jds.setReceiver(friAccount);
//				jds.setSender(account);
				
				
				
				groupChatMsgDataService.init(msg_, account, friAccount,newsType);
				
			}
			
			ar.setSuccess(true);
		
		
		
	
		
		
		
		return ar;
	}
	
	
	@RequestMapping("get_chat_file")
	public void get_chat_img(String filename,HttpServletResponse resp,String type) throws IOException{
		AjaxResp ar=new AjaxResp();
		ar.setSuccess(false);
		
		File file=new File(filename);
		System.out.println("待下载真实文件名"+file.getName()+"   "+file.getAbsolutePath()+"   "+filename);
		if("pic".equals(type)){
			OutputStream out=resp.getOutputStream();
			InputStream in=new FileInputStream(file);
			int temp;
			while((temp=in.read())!=-1){
				out.write(temp);
			}
			in.close();
			out.close();
			return;
		}
		List list=fileUploadService.getFileMapping(file.getName());
		
		if(list.size()==0 || list.isEmpty())
		{
			System.out.println("在数据库中未找到该文件");
			return ;
		}
		FileMapping fm=(FileMapping)list.get(0);
		String oriFileName=fm.getOrifilename();
		
		resp.reset(); 
		resp.setContentType("application/octet-stream; charset=utf-8"); 
		resp.setHeader("Content-Disposition", "attachment; filename=" + oriFileName);
		
		
		
		OutputStream out=resp.getOutputStream();
		InputStream in=new FileInputStream(file);
		int temp;
		while((temp=in.read())!=-1){
			out.write(temp);
		}
		in.close();
		out.close();
		
		
		
	}
	
}
